#include "mainwindow.h"
#include "QMessageBox"
#include "QTime"
#include "QDebug"
#include "ui_mainwindow.h"

void CvImageToQImage(const IplImage* frame, QImage &qimage)
{
    if (!frame) return;
    IplImage* _cvimage;
    if (qimage.isNull())
    {
        qimage = QImage( QSize(frame->width, frame->height), QImage::Format_RGB888 );
    }
    _cvimage = cvCreateImageHeader( cvSize(frame->width, frame->height), 8, 3 );
    _cvimage->imageData = (char *)qimage.bits();
    cvCopy(frame, _cvimage, 0);
    cvCvtColor(_cvimage, _cvimage, CV_BGR2RGB);
}
void CvMatToQimage(const Mat& mat,QImage &qimage) {
    if (!mat.data) return;
    IplImage frame = IplImage(mat);
    IplImage* _cvimage;
    if ( qimage.isNull() )
    {
       qimage = QImage( QSize(frame.width, frame.height), QImage::Format_RGB888 );
    }
    _cvimage = cvCreateImageHeader( cvSize(frame.width, frame.height), 8, 3 );
    _cvimage->imageData = (char *)qimage.bits();
    cvCopy(&frame, _cvimage, 0);
    cvCvtColor(_cvimage, _cvimage, CV_BGR2RGB);
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    running = true;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::msleep(int msecond)
{
    QTime dieTime = QTime::currentTime().addMSecs(msecond);
    while( QTime::currentTime() < dieTime )
    QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void MainWindow::stop_running()
{
    running = false;
}

void MainWindow::on_pb_start_clicked()
{
    IplImage* nFrame = NULL;
    CvCapture* capture = cvCreateCameraCapture(-1);
    if (!capture)
    {
        QMessageBox::information(this,"Camera","No camera found.",QMessageBox::Yes);
        return;
    }
    QImage showImage,diffImage;
    while(running)
    {
        nFrame = cvQueryFrame(capture);
        if(!nFrame) {
            msleep(20);
            break;
        }
        nMat = Mat(nFrame,true);
        opticFlow();

        CvMatToQimage(nMat,showImage);
        ui->label_show->setPixmap(QPixmap::fromImage(showImage));

        CvMatToQimage(dMat,diffImage);
        ui->label_diff->setPixmap(QPixmap::fromImage(diffImage));

        msleep(10);
    }
    cvReleaseCapture(&capture);
}

void MainWindow::opticFlow()
{
    if (!pMat.data){
        nMat.copyTo(pMat);
    }
    dMat = nMat - pMat;
    nMat.copyTo(pMat);
}

void MainWindow::on_pb_stop_clicked()
{
    stop_running();
}
